package dwarffortress.analysis;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;

public class StructureAnalyzer<T> {

    private ArrayList<Field> fields;

    public StructureAnalyzer(Class<T> clazz) {
        fields = new ArrayList<Field>();

        for (Field field :  clazz.getDeclaredFields()) {
            if (!field.isSynthetic() && !Modifier.isStatic(field.getModifiers())) {
                field.setAccessible(true);
                fields.add(field);
            }

        }
    }

    public ObjectAnalyzer<T> analyze(T object) {
        return new ObjectAnalyzer<T>(this, object);
    }

    public int getFieldCount() {
        return fields.size();
    }

    public boolean isArray(int index) {
        return getField(index).getType().isArray();
    }

    public Field getField(int index) {
        return fields.get(index);
    }

    public String getFieldTypeDescription(int i) {
        if (isArray(i)) {
            String typeName;
            Class subtype = getField(i).getType().getComponentType();
            if (subtype.isPrimitive()) {
                typeName = subtype.toString()+"s";
            } else if (subtype.equals(String.class)) {
                typeName = "Strings";
            } else {
                typeName = subtype.getSimpleName();
            }

            return "Array of "  + typeName;
        } else {
            if (getField(i).getType().equals(String.class)) {
                return "String";
            }
            return getField(i).getType().toString();
        }
    }

    public boolean isNumerical(int index) {
        Class<?> type = getField(index).getType();
        if (!type.isPrimitive()) {
            return false;
        }
        if (type.equals(Integer.TYPE) || type.equals(Short.TYPE) || type.equals(Byte.TYPE)) {
            return true;
        }
        return false;


    }

    public boolean isLoadable(int index) {
        return !Modifier.isTransient(getField(index).getModifiers());
    }

    public int getFieldIndexForName(String s) {
        for (int i = 0; i < fields.size(); i++) {
            if (fields.get(i).getName().equals(s)) {
                return i;
            }
        }
        return -1;
    }
}
